import Flutter
import UIKit

class TuyaFlutterViewController: FlutterViewController {
    
    // 标记是否是手动触发的清理，防止循环调用
    var isCleanedUp = false
    var flutterCanPop: Bool = false // 从 Dart 端同步过来的状态
    private var vc: UIGestureRecognizerDelegate?
    
    private lazy var channel: FlutterMethodChannel = FlutterMethodChannel(
        name: "native_to_flutter_tuyavc",
        binaryMessenger: self.binaryMessenger
    )

    override func viewDidLoad() {
          super.viewDidLoad()
          setupChannel()
      }
      
      private func setupChannel() {
          channel.setMethodCallHandler { [weak self] (call, result) in
              guard let self = self else { return }
              // 监听 Dart 主动汇报的状态
              if call.method == "setCanPopInternal" {
                  if let args = call.arguments as? [String: Any],
                     let canPop = args["canPop"] as? Bool {
                      self.flutterCanPop = canPop
                      print("Native received flutter state: canPop = \(canPop)")
                  }
                  result(nil)
              }
             
          }
      }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 2. 接管导航控制器的侧滑代理
        vc = self.navigationController?.interactivePopGestureRecognizer?.delegate;
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
             // 恢复代理，避免影响其他原生页面
        if self.navigationController?.interactivePopGestureRecognizer?.delegate === self {
            self.navigationController?.interactivePopGestureRecognizer?.delegate = vc
        }

        // 判断是 "Back" 操作还是被 "Present" 覆盖
        // isMovingFromParent 在 NavigationController pop 时为 true
        // isBeingDismissed 在 dismiss modal 时为 true
        if self.isMovingFromParent || self.isBeingDismissed {
            cleanupFlutterState()
        }
    }
    
    func cleanupFlutterState() {
        guard !isCleanedUp else { return }
        isCleanedUp = true
        
        // 【关键】通知 Dart 端：我已经退出了，你也把栈顶 pop 掉吧
        // 使用当前 VC 的 binaryMessenger，避免对 engine 的可选/非可选差异做强制解包
        let methodChannel = FlutterMethodChannel(
            name: "native_to_flutter",
            binaryMessenger: self.binaryMessenger
        )
        methodChannel.invokeMethod("popFlutterVC", arguments: nil as Any?)
        
        // 甚至可以通知 engine 此时 detach，释放部分显存资源（可选，视 Flutter 版本而定）
        // self.engine?.viewController = nil
    }
    
    deinit {
        // 双重保险，防止 viewDidDisappear 没触发的情况
        cleanupFlutterState()
        print("TuyaFlutterViewController deinit")
    }

 override   func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
     
     // 只处理侧滑手势
     guard let popGesture = navigationController?.interactivePopGestureRecognizer,
           gestureRecognizer === popGesture else {
         return true // 其他手势（如 ScrollView 里的）放行
     }
     
     // 逻辑分叉：
     if flutterCanPop {
         // 情况 A: Flutter 内部有子页面 (如 FlutterB -> FlutterC)
         // 返回 false -> 禁止 Native 导航栏的侧滑手势
         // 结果 -> 触摸事件会穿透传递给 FlutterView
         // Flutter 内部的 CupertinoPageRoute 会接收到滑动，展示 Flutter 自己的侧滑动画
         return false
     } else {
         // 情况 B: Flutter 在根页面 (FlutterB)
         // 返回 true -> 允许 Native 导航栏的侧滑手势
         // 结果 -> TuyaFlutterViewController 跟随手指滑动退出，露出底下的 NativeB
         return true
     }
 }
}
